package com.come4loves.game.module.skill.helper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.come4loves.game.module.card.constant.CardType;
import com.come4loves.game.module.fight.model.ActorBattle;
import com.come4loves.game.module.fight.model.FightCard;
import com.come4loves.game.module.skill.AbstractTargetCards;

public class TargetHelper {
	public static Logger LOGGER = LoggerFactory.getLogger(TargetHelper.class);

	public static List<FightCard> getTargets(FightCard fightCard, Map<String, Integer> targets, ActorBattle attacker, Collection<ActorBattle> allActorBattles) {
		if (targets.isEmpty()) {
			return Collections.emptyList();
		}
		int target = targets.get("target");
		List<FightCard> cards = new ArrayList<FightCard>();
		if (!targets.containsKey("targettype")) {
			LOGGER.error("targettype error, card id:{},type:{}", fightCard.getCfgId(), fightCard.getCardType());
			return new ArrayList<FightCard>();
		}
		int targetType = targets.get("targettype");
		int race = targets.containsKey("race") ? targets.get("race") : 0;
		int randomNum = targets.containsKey("random") ? targets.get("random") : 0;
		AbstractTargetCards tHandler = AbstractTargetCards.get(targetType);

		switch (target) {
		case 1: // 全军
			for (ActorBattle actorBattle : allActorBattles) {
				cards.addAll(actorBattle.getShowCards().values());
				cards.addAll(actorBattle.getMainCards());
			}
			break;
		case 2: // 我军
			cards.addAll(attacker.getShowCards().values());
			cards.addAll(attacker.getMainCards());
			break;
		case 3: // 友军
			for (ActorBattle actorBattle : allActorBattles) {
				if (actorBattle.getTeam().equals(attacker.getTeam())) {
					cards.addAll(actorBattle.getShowCards().values());
					cards.addAll(actorBattle.getMainCards());
				}
			}
			break;
		case 4: // 敌军
			for (ActorBattle actorBattle : allActorBattles) {
				if (!actorBattle.getTeam().equals(attacker.getTeam())) {
					cards.addAll(actorBattle.getShowCards().values());
					cards.addAll(actorBattle.getMainCards());
				}
			}
			break;

		default:
			break;
		}
		Collection<FightCard> list = tHandler.getTargets(cards, race, randomNum);
		
		if (targets.containsKey("generalid")) {
			Iterator<FightCard> it = list.iterator();
			while (it.hasNext()) {
				FightCard card = it.next();
				if (!card.getCardType().equals(CardType.GENERAL) || card.getCfgId() != targets.get("generalid")){
					it.remove();
				}
				
			}
		}
		List<FightCard> result = new ArrayList<FightCard>();
		result.addAll(list);
		return result;
	}
}
